import axios from 'axios'
import { Message } from 'element-ui'
// import qs from 'qs'

const instance = axios.create({
  baseURL: '',
  // timeout: 5000,
  headers: {},
})

//请求拦截
instance.interceptors.request.use(config => {
  let username = localStorage.getItem('username') || ''
  let roles = Number(localStorage.getItem('role'))
  if(config.method === 'post') {
    config.data = {
      username,
      roles,
      ...config?.data?.data
    }
  } else {
    config.params = {
      username,
      roles,
      ...config.params
    }
  }
  return config;
},error => {
  // console.log(error)
  Message.error({ message: '请求错误' })
  return Promise.reject(error);
})

//响应拦截
instance.interceptors.response.use(response => {
  // console.log(response)
  return new Promise(resolve => resolve(response.data));
}, error => {
  Message.error({ message: '服务器错误' })
  return Promise.reject(error);
})

export const get = instance.get
export const post = instance.post

// 自动拼接username、role
export function initRequestParams() {
  instance.interceptors.request.use(config => {
    // if(config.method === 'post') {
    //   let data = qs.parse(config.data.data);
    //   config.data = qs.stringify({
    //     username: param.username,
    //     role: param.role,
    //     ...data
    //   })
    // } else {
    //   config.params = {
    //     username: param.username,
    //     role: param.role,
    //     ...config.params
    //   }
    // }
    return config;
  },error => {
    return Promise.reject(error);
  })
}

// export function removeRequestParams(){
//   instance.interceptors.request.use(config => {
//     config.method.toString().toLowerCase() === "get"? 
//       config.params = {} : config.data = {}
//     return config;
//   },error => {
//     return Promise.reject(error);
//   })
// }

export default instance

